import { defineStore } from 'pinia'
import {
  login as userLogin,
  logout as userLogout,
  LoginData,
  getUserInfo
} from '@renderer/api/user'
import { setToken, clearToken } from '@renderer/utils/auth'
import { removeRouteListener } from '@renderer/utils/route-listener'
import { UserState } from './types'
import useAppStore from '../app'
export const USER_KEY = 'user-info'
const useUserStore = defineStore('user', {
  state: (): UserState => ({
    isAdmin: 0,
    identityType: 0,
    tenantId: '',
    tenantName: '',
    userType: 0,
    userId: '',
    userAccount: '',
    userName: '',
    fullUserName: '',
    roleNames: '',
    permissionConfigList: [],
    permissionList: [],
    dataPermissionEnable: false,
    dataScope: 0,
    dataIdList: [],
    projectNameList: [],
    rootOrgId: '',
    rootOrgName: '',
    employeeArchivesId: '',
    employeeNumber: 0,
    employeeName: '',
    orgId: '',
    orgPath: '',
    positionName: '',
    ext: '',
    role: 'admin',
    avatar: '',
    phoneNumber: '',
    email: '',
    remark: '',
    enable: 0,
    updatedBy: '',
    updatedDt: '',
    isLongUser: 0,
    dataRoleName: '',
    isWxlogin: 0
  }),

  getters: {
    localUserInfo(): UserState {
      return JSON.parse(localStorage.getItem(USER_KEY)!)
    }
  },

  actions: {
    // Set user's information
    setInfo(partial: Partial<UserState>) {
      this.$patch(partial)
      const userStorage = useStorage(USER_KEY, {}, localStorage, { mergeDefaults: true })
      userStorage.value = null
      userStorage.value = partial
    },

    // Reset user's information
    resetInfo() {
      this.$reset()
    },

    // Login
    async login(loginForm: LoginData) {
      try {
        const res = await userLogin(loginForm)
        setToken(res.data.token)
        this.setInfo(res.data.user)
        const userInfo = await getUserInfo({ userId: res.data.user.userId })
        this.setInfo(userInfo.data)
      } catch (err) {
        clearToken()
        throw err
      }
    },
    logoutCallBack() {
      const appStore = useAppStore()
      this.resetInfo()
      clearToken()
      removeRouteListener()
      appStore.clearServerMenu()
    },
    // Logout
    async logout() {
      try {
        await userLogout()
      } finally {
        this.logoutCallBack()
      }
    }
  }
})

export default useUserStore
